package vip.xiaonuo.modular.manage.order.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.modular.manage.order.entity.BusinessOrderFile;
import vip.xiaonuo.modular.manage.order.enums.BusinessOrderFileExceptionEnum;
import vip.xiaonuo.modular.manage.order.mapper.BusinessOrderFileMapper;
import vip.xiaonuo.modular.manage.order.param.BusinessOrderFileParam;
import vip.xiaonuo.modular.manage.order.param.ParseOrderFile;
import vip.xiaonuo.modular.manage.order.service.IBusinessOrderFileService;
import vip.xiaonuo.modular.manage.tsdatarecord.parser.TableColumn;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.*;

/**
 * BusinessOrderFileServiceImpl
 *
 * @author JackLee
 * 2022/9/7 15:37
 */
@Service
@Slf4j
public class BusinessOrderFileServiceImpl extends ServiceImpl<BusinessOrderFileMapper, BusinessOrderFile> implements IBusinessOrderFileService {

    @Override
    public ParseOrderFile parseFileForView(Long id) {
        BusinessOrderFile orderFile = this.getById(id);
        if (ObjectUtil.isNull(orderFile)) {
            throw new ServiceException(BusinessOrderFileExceptionEnum.NOT_EXIST);
        }
        ParseOrderFile parseOrderFile = new ParseOrderFile();
        List<TableColumn> tableColumns = new ArrayList<>();
        List<Map<String, String>> dataList = new ArrayList<>(5);
        Reader reader = null;
        try {
            reader = new FileReader(orderFile.getFilePath());
            Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(reader);
            Iterator<CSVRecord> recordIterator = records.iterator();
            int i = 0;
            int j = 0;
            //首行 表头
            if (recordIterator.hasNext()) {
                CSVRecord headRecord = recordIterator.next();
                Iterator<String> values = headRecord.iterator();
                while (values.hasNext()) {
                    j++;
                    String value = values.next();
                    TableColumn column = new TableColumn();
                    column.setTitle(value);
                    column.setSort(j);
                    column.setDataIndex("index" + j);
                    tableColumns.add(column);
                }
                j = 0;
            }
            // 获取数据
            while (recordIterator.hasNext() && i < 5) {
                CSVRecord record = recordIterator.next();
                i++;
                Iterator<String> values = record.iterator();
                Map<String, String> data = new HashMap<>();
                while (values.hasNext()) {
                    j++;
                    String value = values.next();
                    data.put("index" + j, value);
                }
                j = 0;
                dataList.add(data);
            }
            parseOrderFile.setTableColumns(tableColumns);
            parseOrderFile.setDataList(dataList);
            return parseOrderFile;
        } catch (FileNotFoundException e) {
            log.error("文件不存在：{}", orderFile.getFilePath());
            throw new ServiceException(BusinessOrderFileExceptionEnum.FILE_NOT_EXIST);
        } catch (IOException e) {
            log.error("文件解析失败：{}", orderFile.getFilePath());
            throw new ServiceException(BusinessOrderFileExceptionEnum.PARSE_FAIL);
        } finally {
            IoUtil.close(reader);
        }
    }

    @Override
    public BusinessOrderFile add(BusinessOrderFile orderFile) {
        this.save(orderFile);
        return orderFile;
    }

    @Override
    public PageResult<BusinessOrderFile> page(BusinessOrderFileParam param) {
        QueryWrapper<BusinessOrderFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByDesc(BusinessOrderFile::getCreateTime);
        if (StringUtils.isNotBlank(param.getFileName())) {
            queryWrapper.lambda().like(BusinessOrderFile::getFileName, param.getFileName());
        }
        if (ObjectUtil.isNotNull(param.getStatus())) {
            queryWrapper.lambda().eq(BusinessOrderFile::getStatus, param.getStatus());
        }
        if (StringUtils.isNotBlank(param.getOrgCode())) {
            queryWrapper.lambda().eq(BusinessOrderFile::getOrgCode, param.getOrgCode());
        }
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }
}
